package com.qing.thread.create;

/**
 * 模拟龟兔赛跑
 */
public class Race implements Runnable {
    public static String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 1000; i++) {
            //作为上帝视角，我想让兔子输，那当我认识到他线程的时候，让他睡眠一会
            if (Thread.currentThread().getName().equals("兔子")) {
                try {
                    Thread.sleep(1);
                    System.out.println("兔子休息一会~");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //先判断是否有人胜出，返回为false则比赛没有结束，返回true则有人胜出，比赛结束！
            boolean flag = gameOver(i);
            if (flag) {
                break;
            }
            System.out.println(Thread.currentThread().getName() + "——>跑了" + i + "步");
        }
    }

    //根据步数判断赛跑是否结束
    public boolean gameOver(int steps) {
        //如果无人胜出，则一直进行比赛
        if (winner != null) {
            return true;
        }
        //如果超过100步，则有人胜利
        if (steps >= 1000) {
            winner = Thread.currentThread().getName();
            System.out.println("胜利者————————》" + winner);
            return true;
        }
        //无人胜出，则一直进行比赛
        return false;
    }


    public static void main(String[] args) {
        Race race = new Race();

        new Thread(race, "乌龟").start();
        new Thread(race, "兔子").start();


    }
}
